package com.qinyu.treehole.controller;

import com.qinyu.treehole.annotation.UserAuth;
import com.qinyu.treehole.entities.R;
import com.qinyu.treehole.tool.FileTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@RestController
@RequestMapping("/api/upload")
@Slf4j
@Validated
public class UploadController {


    private DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd-");

    @UserAuth
    @PostMapping("/avatar")
    public R uploadAvatar(@RequestParam("file")MultipartFile file,
                          @RequestParam("userId") Integer userId){
        if (file.isEmpty()){
            return R.no(null, FileTool.UPLOAD_FILE_EMPTY);
        }

        LocalDateTime now = LocalDateTime.now();
        String fileName = formatter.format(now) + Math.random() + ".png";
        String filePath = FileTool.AVATAR_UPLOAD_PATH + fileName;
        log.info("用户id:{}上传文件path:{}", userId, filePath);

        File newFile = new File(filePath);

        if (!newFile.exists()){
            newFile.mkdirs();
        }

        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            return R.no(null, FileTool.AVATAR_UPLOAD_FAIL);
        }

        return R.ok(FileTool.AVATAR_UPLOAD_PREFIX + fileName, FileTool.AVATAR_UPLOAD_SUCCESS);
    }
}
